package com.common.activity.clip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.StarAppConst;
import com.common.activity.StarAppBaseFramentActivity;
import com.common.allCommon.CommUtil;
import com.common.allCommon.ImageUploadUtils;
import com.common.android.utils.ToastUtils;
import com.common.android.utils.task.progressTask.ProgressTask;
import com.common.utils.StarAppUtils;
import com.common.widget.ClipCircleView;
import com.common.widget.CommonActivityTitle;
import com.common.widget.CommonActivityTitle.TitleBtnCallback;
import com.common.widget.StarappToast;
import com.starappallcommon.R;

/**
 * 截取圆形图片
 * 
 * <br>
 * Created 2014-5-5 下午2:37:09
 * 
 * @version
 * @author HuangYK
 * 
 * @see
 */
public class StarAppClipCirclePictureActivity extends
		StarAppBaseFramentActivity implements OnTouchListener, OnClickListener {
	/** 裁剪完成返回数据的KEY */
	public static final String RESULT_KEY = "BITMAP";

	/** 要裁剪图片的本地路径 */
	public static final String PRIMARY_BITMAP_PATH = "primary_bitmap_path";
	/** 要裁剪图片的uri */
	public static final String PRIMARY_BITMAP_URI = "primary_bitmap_uri";

	/** 上下文 */
	private Activity mActivity;

	/** 状态栏高度 */
	private int mStatusBarHeight = 0;

	/** 顶部Title */
	private CommonActivityTitle mCommonActivityTitle;

	/** 顺时针旋转 */
	private TextView mTvClockwiseRotate;

	/** 逆时针旋转 */
	private TextView mTvContraRotate;

	/** 待裁剪的原图 */
	private Bitmap mPrimaryBitmap;

	/** 展示原图的ImageView */
	private ImageView mIvPrimaryBitmap;

	/** 确认按钮 */
	private Button mBtnConfirm;
	/** 圆形裁剪蒙板 */
	private ClipCircleView mClipCircleView;

	// 控制移动和缩放图像
	private Matrix mMatrix = new Matrix();
	private Matrix mSavedMatrix = new Matrix();

	// 三种操作状态
	/** 无操作标志 */
	private static final int NONE = 0;
	/** 拉伸图片标志 */
	private static final int DRAG = 1;
	/** 放大、缩小图片的标志 */
	private static final int ZOOM = 2;
	/** 当前模式标志位 */
	private int mMode = NONE;

	/** 单点操作 */
	private PointF mStart = new PointF();
	/** 多点操作 */
	private PointF mMid = new PointF();
	/** 旧的距离 */
	private float mOldDist = 1f;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View contentView = LayoutInflater.from(this).inflate(
				R.layout.startapp_clip_picture_activity, null);

		StarAppUtils.hideBottomSmartbar(this, contentView);

		setContentView(contentView);
		mActivity = this;
		initView();
		initTypeFace();
		initDataFromIntent();
		// initEvent();
		// initClipView();
	}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mActivity = null;
        mTvClockwiseRotate = null;
        mTvContraRotate = null;
        if (mPrimaryBitmap != null && !mPrimaryBitmap.isRecycled()) {
            mPrimaryBitmap.recycle();
        }
        mPrimaryBitmap = null;
        mIvPrimaryBitmap = null;
        mBtnConfirm = null;
        Bitmap bmp = ((BitmapDrawable) mClipCircleView.getBackground()).getBitmap();
        if (bmp != null && !bmp.isRecycled()) {
            mClipCircleView.setBackgroundDrawable(null);
            bmp.recycle();
        }
        bmp = null;
        mClipCircleView = null;
        mMatrix.reset();
        mMatrix = null;
        mSavedMatrix.reset();
        mSavedMatrix = null;
        mStart = null;
        mMid = null;
    }

    /**
	 * 初始化组件显示文字字体 <br>
	 * Created 2014-8-22 下午2:06:05
	 * 
	 * @author ChuXY
	 */
	private void initTypeFace() {
		StarAppUtils.setViewTypeFace(mBtnConfirm, true);
		StarAppUtils.setViewTypeFace(mTvClockwiseRotate, false);
		StarAppUtils.setViewTypeFace(mTvContraRotate, false);
		mCommonActivityTitle.setTitleTextTypeface(StarAppConst.getInstance()
				.getLTXTypeface(), true);
	}

	/**
	 * 初始化视图
	 * 
	 * <br>
	 * Created 2014-5-5 下午4:34:33
	 * 
	 * @author : HuangYK
	 */
	private void initView() {
		mCommonActivityTitle = (CommonActivityTitle) findViewById(R.id.common_activity_title);
		mIvPrimaryBitmap = (ImageView) findViewById(R.id.ivPrimaryBitmap);
		mBtnConfirm = (Button) findViewById(R.id.btnConfirm);
		mTvClockwiseRotate = (TextView) findViewById(R.id.tvContrarotate);
		mTvContraRotate = (TextView) findViewById(R.id.tvClockwiseRotate);

	}

	/**
	 * 初始化数据
	 * 
	 * <br>
	 * Created 2014-5-5 下午4:34:38
	 * 
	 * @author : HuangYK
	 */
	private void initDataFromIntent() {
		Intent intent = getIntent();
		if (intent == null) {
			finish();
			return;
		}
		String stringExtra = "";
		// 图片路径数据
		if (intent.hasExtra(PRIMARY_BITMAP_PATH)) {
			stringExtra = intent.getStringExtra(PRIMARY_BITMAP_PATH);

			new LoadingBitmap(this, 0, stringExtra).execute();
			// if (new File(stringExtra).exists()) {
			// Options options = new Options();
			// options.inSampleSize = 2;
			// while (true) {
			// try {
			// mPrimaryBitmap = BitmapFactory.decodeStream(
			// new FileInputStream(stringExtra), null,
			// options);
			// break;
			// } catch (OutOfMemoryError e) {
			// options.inSampleSize *= 2;
			// continue;
			// }
			// }
			// }
		} else if (intent.hasExtra(PRIMARY_BITMAP_URI)) {
			// 图片URI数据
			stringExtra = intent.getStringExtra(PRIMARY_BITMAP_URI);
			if (TextUtils.isEmpty(stringExtra)) {
				return;
			}
			Uri uri = Uri.parse(intent.getStringExtra(PRIMARY_BITMAP_URI));
			mPrimaryBitmap = StarAppClipUtil.decodeUriAsBitmap(this, uri);
		}
		// // 如果图片都获取不到，关闭
		// if (mPrimaryBitmap == null) {
		// finish();
		// return;
		// }
		// mIvPrimaryBitmap.setImageBitmap(mPrimaryBitmap);
	}

	/**
	 * 初始化监听事件
	 * 
	 * <br>
	 * Created 2014-5-5 下午4:34:43
	 * 
	 * @author : HuangYK
	 */
	protected void initEvent() {
		mCommonActivityTitle.setTitleBtnCallback(mTitleBtnCallback);
		mIvPrimaryBitmap.setOnTouchListener(this);
		mIvPrimaryBitmap.requestFocus();
		mBtnConfirm.setOnClickListener(this);
		mTvClockwiseRotate.setOnClickListener(this);

		mTvContraRotate.setOnClickListener(this);
	}

	/**
	 * 初始化裁剪视图
	 * 
	 * <br>
	 * Created 2014-5-5 下午4:34:47
	 * 
	 * @author : HuangYK
	 */
	private void initClipView() {
		if (mClipCircleView == null) {
			mClipCircleView = (ClipCircleView) this
					.findViewById(R.id.clipCircleView);
		}
		int mContentW = mClipCircleView.getWidth();
		int mContentH = mClipCircleView.getHeight();

		// 获取状态栏的高度
		if (mStatusBarHeight == 0) {
			mStatusBarHeight = StarAppClipUtil.getBarHeight(this);
		}
		// 判断mClipCircleView是否已获得宽高，以及是否成功获取状态栏高度，未获得，重新初始化
		if (mContentW == 0 || mClipCircleView == null || mStatusBarHeight == 0) {
			Message msg = mHandler.obtainMessage();
			msg.what = OBTAIN_VIEW;
			mHandler.sendMessage(msg);
			return;
		}
		// 设置裁剪蒙板
		mClipCircleView.initBg( StarAppUtils.getInstance().readDisplayMetrics().x ,  StarAppUtils.getInstance().readDisplayMetrics().y,
				mStatusBarHeight);

		// StarAppClipUtil.reSetImageMatrix(mMatrix, mPrimaryBitmap, mContentW,
		// mContentH);
		// mIvPrimaryBitmap.setImageMatrix(mMatrix);
		// mIvPrimaryBitmap.postInvalidate();

		Matrix matrix = new Matrix();
		StarAppClipUtil.reSetImageMatrix(matrix, mPrimaryBitmap, mContentW,
				mContentH);
		matrix.postRotate(0, mPrimaryBitmap.getWidth() / 2,
				mPrimaryBitmap.getHeight() / 2);

        try {
            mPrimaryBitmap = Bitmap.createBitmap(mPrimaryBitmap, 0, 0,
                    mPrimaryBitmap.getWidth(), mPrimaryBitmap.getHeight(), matrix,
                    true);
        } catch (OutOfMemoryError error) {

        }

        mIvPrimaryBitmap.setImageBitmap(mPrimaryBitmap);
		StarAppClipUtil.reSetImageMatrix(mMatrix, mPrimaryBitmap, mContentW,
				mContentH);
		mIvPrimaryBitmap.getImageMatrix().reset();
		mIvPrimaryBitmap.setImageMatrix(mMatrix);
		mIvPrimaryBitmap.invalidate();
	}

	/** 获取View大小的handler标志位 */
	private final static int OBTAIN_VIEW = 1;
	/**
	 * 用来初始化ClipView
	 */
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case OBTAIN_VIEW:
				initClipView();
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 这里实现了多点触摸放大缩小，和单点移动图片的功能
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:30:51
	 * 
	 * @param v
	 *            视图
	 * @param event
	 *            事件
	 * @return 是否继续操作
	 * @author : HuangYK
	 */
	public boolean onTouch(View v, MotionEvent event) {

		ImageView view = (ImageView) v;
		// 最小有效值
		final float minOffset = 10f;
		// 处理触摸事件
		switch (event.getAction() & MotionEvent.ACTION_MASK) {

		case MotionEvent.ACTION_DOWN:
			// 单点监听
			mSavedMatrix.set(mMatrix);
			// 设置初始位置
			mStart.set(event.getX(), event.getY());
			mMode = DRAG;
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
			// 多点监听
			mOldDist = StarAppClipUtil.spacing(event);
			if (mOldDist > minOffset) {
				mSavedMatrix.set(mMatrix);
				StarAppClipUtil.midPoint(mMid, event);
				mMode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			mMode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mMode == DRAG) {
				mMatrix.set(mSavedMatrix);
				mMatrix.postTranslate(event.getX() - mStart.x, event.getY()
						- mStart.y);
			} else if (mMode == ZOOM) {
				Matrix mtx = new Matrix(mMatrix);

				float newDist = StarAppClipUtil.spacing(event);
				if (newDist > minOffset) {
					mtx.set(mSavedMatrix);
					float scale = newDist / mOldDist;
					mtx.postScale(scale, scale, mMid.x, mMid.y);
				}

				float[] values = new float[9];
				mtx.getValues(values);
				if (values[Matrix.MSCALE_X] > 2.0f
						|| values[Matrix.MSCALE_Y] > 2.0f
						|| values[Matrix.MSCALE_X] < 0.1f
						|| values[Matrix.MSCALE_Y] < 0.1f) {
					break;
				}

				mMatrix = new Matrix(mtx);
			}
			break;
		default:
			break;
		}
		view.setImageMatrix(mMatrix);
		return true;
	}

	/**
	 * 点击确认
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:32:07
	 * 
	 * @param v
	 *            视图
	 * @author : HuangYK
	 */
	public void onClick(View v) {
		final int vId = v.getId();
		// 确认裁剪
		if (vId == R.id.btnConfirm) {
			// 无网络
			if (!CommUtil.JudgeNetWorkStatus(mActivity)) {
				ToastUtils.display(mActivity,
						R.string.common_network_error_to_network);
				return;
			}

			// 获取裁剪后的图片
			Bitmap finaBitmap = mClipCircleView.getClipBitmap(StarAppClipUtil
					.takeScreenShot(StarAppClipCirclePictureActivity.this));
			// 统一缩放为600*600
			finaBitmap = Bitmap.createScaledBitmap(finaBitmap,
					StarAppClipUtil.MAX_AVATOR_SIZE,
					StarAppClipUtil.MAX_AVATOR_SIZE, true);

			// 获取软件在SD卡上的私有缓存路径
			String tmpPath = StarAppUtils.getSDCardCacheDir(getBaseContext());
			if (TextUtils.isEmpty(tmpPath)) {
				// 获取不到路径则返回失败
				resultFail();
			} else {
				// 在软件私有缓存路径下创建一个临时的头像裁剪文件
				File file = new File(tmpPath,
						StarAppClipUtil.TEMP_AVATOR_CLIP_NAME);
				tmpPath = file.getPath();
				try {
					// 将图片存为文件保存在本地
					StarAppClipUtil
							.compressImageAndSave(finaBitmap, tmpPath, 0);
				} catch (IOException e) {
					ToastUtils.display(StarAppClipCirclePictureActivity.this,
							R.string.clip_file_save_fail);
					return;
				}
				// 裁剪成功则返回成功标识
				Intent intent = new Intent();
				intent.putExtra(RESULT_KEY, tmpPath);
				setResult(RESULT_OK, intent);
				finish();
			}
			return;
		}

		// 逆时针旋转
		if (vId == R.id.tvContrarotate) {
			doRotate(true);
			return;
		}

		// 顺时针旋转
		if (vId == R.id.tvClockwiseRotate) {
			doRotate(false);
			return;
		}

	}

	/**
	 * 旋转图片
	 * 
	 * <br>
	 * Created 2014-5-19 下午8:24:09
	 * 
	 * @param isContrarotate
	 *            是否逆时针旋转
	 * @author : HuangYK
	 */
	private void doRotate(boolean isContrarotate) {
		mMatrix = new Matrix();
		int mContentW = mClipCircleView.getWidth();
		int mContentH = mClipCircleView.getHeight();
		int degrees = 0;
		final int defaultValue = 90;
		if (isContrarotate) {
			degrees = 0 - defaultValue;
		} else {
			degrees = defaultValue;
		}
		Matrix matrix = new Matrix();
		StarAppClipUtil.reSetImageMatrix(matrix, mPrimaryBitmap, mContentW,
				mContentH);
		matrix.postRotate(degrees, mPrimaryBitmap.getWidth() / 2,
				mPrimaryBitmap.getHeight() / 2);
        try {
            mPrimaryBitmap = Bitmap.createBitmap(mPrimaryBitmap, 0, 0,
                    mPrimaryBitmap.getWidth(), mPrimaryBitmap.getHeight(), matrix,
                    true);
        } catch (OutOfMemoryError error) {

        }

		mIvPrimaryBitmap.setImageBitmap(mPrimaryBitmap);
		StarAppClipUtil.reSetImageMatrix(mMatrix, mPrimaryBitmap, mContentW,
				mContentH);
		mIvPrimaryBitmap.getImageMatrix().reset();
		mIvPrimaryBitmap.setImageMatrix(mMatrix);
		mIvPrimaryBitmap.invalidate();
	}

	/**
	 * 失败返回
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:33:35
	 * 
	 * @author : HuangYK
	 */
	private void resultFail() {
		setResult(RESULT_CANCELED);
		finish();
	}

	/**
	 * 顶部按钮点击监听
	 */
	private TitleBtnCallback mTitleBtnCallback = new TitleBtnCallback() {

		@Override
		public void onBtnClick(int clickType) {
			finish();
		}
	};

	/**
	 * 加载图片操作
	 * 
	 * <br>
	 * Created 2014-6-9 下午9:51:23
	 * 
	 * @version StarAppClipCirclePictureActivity
	 * @author HuangYK
	 * 
	 * @see
	 */
	private class LoadingBitmap extends ProgressTask {
		private String mFilePath = "";

		public LoadingBitmap(Context context, int resId, String filePath) {
			super(context, R.string.image_loading);
			mFilePath = filePath;
			progressDialogIteration = new IProgressDialogIteration() {

				@Override
				public void onShow() {
					mPd.show();
				}

				@Override
				public void onDismiss() {
					if ((mPd != null) && (mPd.isShowing())) {
						mPd.dismiss();
					}
					if (isCancelled()) {
						mActivity.finish();
					}
				}
			};
		}

		@Override
		protected void doSuccess() {
			// 如果图片都获取不到，关闭
			if (mActivity == null || mActivity.isFinishing()) {
				return;
			}
			if (mPrimaryBitmap == null) {
				finish();
				return;
			}
            try {
                mIvPrimaryBitmap.setImageBitmap(mPrimaryBitmap);
                mIvPrimaryBitmap.postInvalidate();
            }catch (OutOfMemoryError e){
                StarappToast.show(mActivity, getString(R.string.out_of_memory_tip), 0);				
				finish();
				return;
            }
			initEvent();
			initClipView();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			if (mActivity == null || mActivity.isFinishing()) {
				return;
			}
			StarAppClipCirclePictureActivity.this.finish();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			if (new File(mFilePath).exists()) {
				Options options = new Options();
				options.inSampleSize = 2;
				while (true) {
					try {
						if (isCancelled()) {
							return -1;
						}
						mPrimaryBitmap = BitmapFactory.decodeStream(
								new FileInputStream(mFilePath), null, options);

						int degree = ImageUploadUtils.getDegree(mFilePath);
						// 如果旋转角度 > 0,则需要旋转回正确的方向
						if (degree > 0) {
							mPrimaryBitmap = ImageUploadUtils.rotateBitmap(
									mPrimaryBitmap, degree);
						}
						break;
					} catch (OutOfMemoryError e) {
						if (options == null) {
							options = new Options();
							options.inSampleSize = 2;
							continue;
						}
						options.inSampleSize *= 2;
						continue;
					} catch (FileNotFoundException e) {
						return -1;
					}
				}
			}
			return 0;
		}
	}

}